package com.zuxia.struts2.inter.dao;

import com.zuxia.struts2.base.exception.MyException;
import com.zuxia.struts2.base.util.HibernateUtils;
import com.zuxia.struts2.inter.entity.CookinfoEntity;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.util.List;

public class CookDao {
    Session session=null;
    Transaction transaction=null;

    /*
     * 查询是否有该用户
     * 接受传递集合中的用户名字和密码
     * */
    public Boolean CookLogin(CookinfoEntity cookinfoEntity) throws MyException {
        List list = null;
        try {
            //加载工厂
            session = HibernateUtils.getSession();
            // 1、得到query对象，并写入hql语句
            Query query = session.createQuery("from CookinfoEntity where cookName =? and cookPassword = ?");
            //填写站位符，根据id查询数据
            query.setParameter(0,cookinfoEntity.getCookName());
            query.setParameter(1,cookinfoEntity.getCookPassword());
            //使用query对象的list对象得到数据
            list = query.list();

        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("数据库异常，请联系管理员！");
        }finally {
            session.close();
        }
        if (list.size()==0){
            throw new MyException("登陆失败,请检查你的密码和账号是否正确");
        }

        return true;
    }


    /**
     * 查用户密码的盐值
     * @param cookName
     * @return
     * @throws MyException
     */
    public String selectSalt(String cookName) throws MyException {
        List list = null;
        try {
            //加载工厂
            session = HibernateUtils.getSession();
            Query query = session.createQuery("from CookinfoEntity where cookName =?");
            query.setParameter(0,cookName);
            list = query.list();

        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("数据库异常，请联系管理员！");
        }finally {
            session.close();
        }
        if (list.size()==0) {
            throw new MyException("登陆失败,请检查你的密码和账号是否正确！");
        }
        return ((CookinfoEntity)list.get(0)).getSalt();
    }
}
